package com.yanqingying.Filter;

import com.yanqingying.JwtsTest;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import java.io.IOException;


@Slf4j
//@WebFilter("/*")
public class loginFileter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String requestURI = req.getRequestURI();
        if (requestURI.contains("login")){
            filterChain.doFilter(servletRequest, servletResponse);

            return;
        }
        try {
            String token = req.getHeader("token");
            if (token == null){
                resp.setStatus(HttpStatus.UNAUTHORIZED.value());
                return;
            }
            Claims claims = JwtsTest.JwtParser(token);
            log.info("claims = {}",claims);
        } catch (Exception e) {
            resp.setStatus(HttpStatus.UNAUTHORIZED.value());
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
